<?php
namespace Apipad\Controller;
use Think\Controller;
class ComController extends \Common\Controller\BaseIpadmtController {

    protected $uinfo = ''; //用户基本信息
    protected $allow_update_field = '*'; //允许修改字段
    protected $batchAddPk = ''; //批量添加主字段,只能填一个
    protected $allow_del = 0;
    protected $kh_uid = 0;//客户ID

    //初始化
    function _initialize() {
        parent::_initialize();
        $controller = CONTROLLER_NAME; //控制器
        $action = ACTION_NAME; //操作
        $this->post=$_POST;
        $user_msg = $this->uinfo;
        $this->auth($user_msg);
    }

    //权限验证
    function auth($user_msg){
        if(!$user_msg && CONTROLLER_NAME!='Public'){
            $data_cc['code'] = 101;
            $data_cc['msg'] = "请先登录";
            exit(json_encode($data_cc));
        }
        
    }

    //列表读取限制
    function _before_index(){
    
    }

    //兼容
    function lists(){
        $this->index();
    }

    /**
     * 列表页
     */
    public function index($model='') {
        //生成查询条件
        $name = CONTROLLER_NAME;
        //检查过滤
        $this->check();
        $model = $model ? : D($name);
        //列表过滤器，生成查询Map对象
        if(method_exists($model,'_search')){
            $map = $model->_search();
        }else{
            $map = $this->_search();
        }
        
        if (method_exists($this, '_filter')) {
            $this->_filter($map);
        }
        if (!empty($model)) {
            if(method_exists($model,'_list')){
                $data = $model->_list($model, $map);
            }else{
                $data = $this->_list($model, $map);
            }
        }
      
        $msg['data'] = $data;
        $this->ajaxSucReturn($msg);
    }

    //分页组装
    function getPage($count, $limit=20){
        $p = new \Think\AdminPage($count, $limit);
        $return['page_count'] = $p->totalPages;//总页数
		$return['page_count'] = $p->totalPages;//总页数
		$return['count'] = $p->totalRows;//总条数
        $return['listRows'] = $p->listRows;//总条数
		$return['now_page'] = $p->nowPage;
        return $return;
    }

    //全部数据树形
    function getTreeList()
    {
        $model = D(CONTROLLER_NAME);
        $map = $this->_search();
        $data = $model->getList($map, 10000, 'pid asc,id asc');
        $tree = new \Think\Tree($data['list']);
        $tree->key_field = 'id'; //主键字段名
        $tree->name_field = 'title'; //主键字段名
        $tree->fid_field = 'pid'; //父节点字段名
        $c_list = $tree->get_tree(0);
        $this->ajaxSucReturn($c_list);
    }

    //全部数据数组
    function getArrList(){
        $model = D(CONTROLLER_NAME);
        $wdata['pid'] = 0;
        $wdata['status'] = I('status') ? : 3;//默认设计师款式
        $list = $model->where($wdata)->select();
        foreach($list as &$val){
            if($val['child_num']>0){
                $val['childs'] = $this->digui($val);
            }
        }
        $this->ajaxSucReturn($list);
    }

    //递归
    function digui($val){
        $model = D(CONTROLLER_NAME);
        $wdata['pid'] = $val['id'];
        $dlist = $model->where($wdata)->select() ? : [];
        foreach($dlist as &$dval){
            if($dval['child_num']>0){
                $dval['childs'] = $this->digui($dval);
            }
        }
        return $dlist;
    }

    //检查控制器是否存在
    function check(){
        //判断模型是否存在
        $have_cont = false;
        $cont_name = CONTROLLER_NAME.'Controller.class.php';

        //当前控制器位置
        $use_cont_dir = APP_PATH.MODULE_NAME.'/Controller/'.$cont_name;
        if(is_file($use_cont_dir)){
            $have_cont = true;
        }
        //核心控制器位置
        $com_cont_dir = APP_PATH.'Api/Controller/'.$cont_name;
        if(is_file($com_cont_dir)){
            $have_cont = true;
        }
        if(!$have_cont){
            //dump($com_cont_dir);dump($use_cont_dir);exit;
            //控制器不存在
            $this->ajaxErrReturn('你访问的页面不存在!');
        }
    }

    /**
     * 上传图片
     * $options 
     */
    function upload($options = array()){
        $config['maxSize'] = 1024*1024*(C('upload_size') ? : 2);
        $config['exts'] = array('jfif','jpg','jpeg','gif','png','swf','xls','xlsx','txt');
        $config['saveRule'] = 'uniqid';
        //$config['rootPath'] = './Uploads/';
        $config['rootPath'] = 'Uploads/';
        $config['savePath'] = '';
        //$config['subName'] = date('Y/m/d');
        $config['subName'] = array('date', 'Y/m/d');
        //$config['driver'] = C('FILE_UPLOAD_TYPE') ? C('FILE_UPLOAD_TYPE') : 'Local';
        $config['driver'] = 'AliOss';
        if($options){
            $config = array_merge($config,$options);
        }
        $upload = new \Think\Upload($config);
        $info = $upload->upload();
        //dump($info);exit;
        if($info){
            foreach($info as &$file){
                $key = $file['key'];
                if($config['driver']=='Local'){
                    $_POST[$key] = '/Uploads/'.$file['savepath'].$file['savename'];//存相对路径
                    $result['filepath'][$key] = $file['savepath'].$file['savename'];//存相对路径
                    $result['url'][$key] = '/Uploads/'.$file['savepath'].$file['savename'];//绝对路径
                }else if($config['driver']=='AliOss'){
                    $bo_model = M('BasetOss');
                    $bo_vo = $bo_model->find();
                    //阿里云
                    $_POST[$key] = $bo_vo['return_url'].'/'.$file['savepath'].$file['savename'];//存相对路径
                    $result['filepath'][$key] = $file['savepath'].$file['savename'];//存相对路径
                    $result['url'][$key] = $bo_vo['return_url'].'/'.$file['savepath'].$file['savename'];//绝对路径
                }
                $file['rootPath'] = $config['rootPath'] ? : '';
                $file['savePath'] = $config['savePath'] ? : '';
            }
            $result['status'] = 1;
            $result['data'] = $info;
        }else{
            $result['status'] = 0;
            $result['error'] = $upload->getError();
        }
 
        return $result;
    }

    /**
     * 图片路径处理
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getPicUrl($value){
        $pic_url = '';
        if($value){
            $preg = "/^http(s)?:\\/\\/.+/";
            if(preg_match($preg,$value)){
                $pic_url =  $value;//完整url
            }else{
                $model = M('System');
                $vo = $model->find();
                $Wimgurl = $vo['sUrl'];
                if(C('aliyun_oss')){
                    $pic_url =  C('aliyun_oss.url').'/'.$value;
                }else{
                    $pic_url =  $Wimgurl.$value;
                }
            }
        }
        return $pic_url;
    }

   /**
     +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     +----------------------------------------------------------
     * @access protected
     +----------------------------------------------------------
     * @param string $name 数据对象名称
     +----------------------------------------------------------
     * @return HashMap
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    public function _search($name = '') {
        //生成查询条件
        if (empty($name)) {
            $name = CONTROLLER_NAME;
        }
        $model = D($name);
        $map = array();
		//前置执行
		if(method_exists($this,'_before_search')){
			$map = $this->_before_search();
		}
        foreach ($model->getDbFields() as $key => $val) {
            if (isset($_REQUEST [$val]) && $_REQUEST [$val] !== '') {
                $this->assign($val, $_REQUEST [$val]);
                //dump(C('DB_LIKE_FIELDS'));exit;
                if (C('DB_LIKE_FIELDS')) {
                    $like_keys = explode('|', C('DB_LIKE_FIELDS'));
                    if (in_array($val, $like_keys)) {
                        $map [$val] = array('like', '%' . $_REQUEST [$val] . '%');
                    } else {
                        $map [$val] = $_REQUEST [$val];
                    }
                } else {
                    $ar = explode(',',$_REQUEST [$val]);
                    if(count($ar)>1){
                        $map [$val] = array('in',$ar);
                    }else{
                        $map [$val] = $_REQUEST [$val];
                    }
                }
            }
        }
        // dump($map);exit;
		//后置执行
		if(method_exists($this,'_after_search')){
			$_after_map = $this->_after_search();
			if($_after_map)$map = array_merge($map,$_after_map);
		}
        return $map;
    }

    /**
     +----------------------------------------------------------
     * 根据表单生成查询条件 (无模型进入此处)
     * 进行列表过滤
     +----------------------------------------------------------
     * @access protected
     +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     */
    public function _list($model, $map, $listRows=20, $sortBy = '', $asc = false) {
        $_REQUEST = I('request.');
        //排序字段 默认为主键名
        if($sortBy){
            //自定义
            $order = $sortBy;
        }else{
            //传参拼接
            if ($_REQUEST ['_order']) {
                $_order = $_REQUEST ['_order'];
            } else {
				if(is_array($model->getPk())){
					$_order =  end($model->getPk());
				}else{
					$_order = $model->getPk();
				}
            }
            //排序方式默认按照倒序排列
            //接受 sost参数 0 表示倒序 非0都 表示正序
            if ($_REQUEST ['_sort']) {
                if(is_numeric($_REQUEST ['_sort'])==true){
                    $_sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
                }else{
                    $_sort = $_REQUEST ['_sort']=='asc' ? 'asc' : 'desc';
                }
            } else {
                $_sort = $asc ? 'asc' : 'desc';
            }
            $order = "`" . $_order . "` " . $_sort;
        }
        //取得满足条件的记录数
        $count = $model->where($map)->count();
		//echo M()->_sql();exit;
        if (!empty($_REQUEST ['limit'])) {
            $listRows = $_REQUEST ['limit'];
        } else {
            $page_size = C('page_size');
            $listRows = $page_size ? $page_size : 20;
        }
        $page_count = ceil($count / $listRows);
        if ($count > 0) {
            //创建分页对象
            $p = new \Think\AdminPage($count, $listRows);
            //分页查询数据

            $voList = $model->field($this->field)->where($map)->order($order)->limit($p->firstRow . ',' . $p->listRows)->select();
            //echo M('')->getlastsql();exit;
            //分页跳转的时候保证查询条件
            foreach ($map as $key => $val) {
                if (!is_array($val)) {
                    $p->parameter .= "$key=" . urlencode($val) . "&";
                }
            }
            //分页显示
            $page = $p->show();

            //列表排序显示
            $sortImg = $sort; //排序图标
            $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
            $sort = $sort == 'desc' ? 1 : 0; //排序方式
        }else{
			$p = new \Think\AdminPage($count, $listRows);
			$voList = [];
			$page = $p->show();
		}
        $data['list'] = $voList;
		$data['page_count'] = $p->totalPages;//总页数
		$data['count'] = $p->totalRows;//总条数
        $data['limit'] = $p->listRows;//总条数
		$data['now_page'] = $p->nowPage;
        return $data;
    }

    /**
     * 添加数据
     */
    public function add() {
        if (IS_POST) {
            $model = D(CONTROLLER_NAME);
            $_POST['uid'] = UID;
            if ($this->checkFileUp()) {
                $this->upload();
            }
            $data = $model->create();
            if (false === $data) {
                $this->ajaxErrReturn($model->getError());
            }
            foreach($data as $field=>$val){
                if(is_array($val)){
                    //数组转化为字符串
                    $data[$field] = implode(',',$val);
                }
            }
 
            //保存当前数据对象
            $list = $model->add($data);
            //echo M()->_sql();exit;
            if ($list !== false) { //保存成功
                $this->history($list);
                if (method_exists($this, '_after_add')) {
                    $this->_after_add($list);
                }
                //缓存判断
                if (method_exists($this, 'GiveCache')) {
                    //缓存判断(控制器)
                    $this->GiveCache($list);
                }else if (method_exists($model, 'GiveCache')) {
                    //缓存判断(模型)
                    $model->GiveCache($list);//无需提示
                }
                $msg['msg'] = '新增成功';
                $msg['data'] = $list;
                $this->ajaxSucReturn($msg);
            } else {
                //失败提示
                $this->ajaxErrReturn($model->getError());
            }
        }
    }

    //批量添加
    function batchAdd(){
        $post = I('post.');
        $array_keys = array_keys($post);
        foreach($array_keys as $array_val){
            if($array_val!='token'){
                $post_fields[] = $array_val;
            }
        }
        $required_field = $this->batchAddPk ? : $post_fields[0];
        if(!$post[$required_field]){
            $this->ajaxErrReturn($required_field.'字段必须');
        }
        $model = D(CONTROLLER_NAME);
        $model->startTrans();
        foreach($post[$required_field] as $key=>$val){
            if(!$post[$required_field][$key]){
                $this->ajaxErrReturn($required_field.'字段必须');
            }
            foreach($post_fields as $field){
                $input[$field] = $post[$field][$key];
            }
            $input['aid'] = UID;
            $input['aname'] = $this->uinfo['aName'] ? : '';
            $input['add_time'] = NOW_TIME;
            //验证数据
            $data = $model->create($input);
            if (false === $data) {
                $this->ajaxErrReturn($model->getError());
            }
            $id = $model->add($data);
            if (false === $id) {
                $this->ajaxErrReturn('添加失败');
            }
            $ids[] = $id;
            $this->history($id);//历史操作记录
        }
        $model->commit();
        $return['data'] = implode(',',$ids);
        $return['msg'] = '添加成功';
        $this->ajaxSucReturn($return);
    }

    //上传图片
    public function savemoreimgc()
    {

        $info = $this->upload();
        if($info['url']['upfile']){
            echo json_encode(['status' => 1, 'msg' => '上传成功','url' => $info['url']['upfile']]);exit;
        }else{
            echo json_encode(['status' => 0, 'msg' => '上传失败']);exit;
        }
    }

    /**
     * 编辑数据
     */
    public function edit() {
		$name = CONTROLLER_NAME;
		$model = D($name);
        $pk = $model->getPk();
        $id = $_REQUEST [$model->getPk()];
        if(!$id){
            $this->ajaxErrReturn('主键必须');
        }
        $wdata['uid'] = UID;
        $wdata[$pk] = $id;
        $vo = $model->where($wdata)->find();
        if(!$vo){
            $this->ajaxErrReturn('数据不存在');
        }
        if (IS_POST) {
            $_POST['edit_time'] = NOW_TIME;
            if ($this->checkFileUp()) {
                //上传新图
                $options = array();
                $this->upload($options);
            }
            $data = $model->create();
            if (false === $data) {
                $this->ajaxErrReturn($model->getError());
            }
            foreach($data as $field=>$val){
                if(is_array($val)){
                    //数组转化为字符串
                    $data[$field] = implode(',',$val);
                }
            }
            //过滤可以修改的字段
            if($this->allow_update_field!='*'){
                if(!is_array($this->allow_update_field)){
                    //转数组
                    $allow_update_field = explode(',',$this->allow_update_field);
                }else{
                    $allow_update_field = $this->allow_update_field;
                }
                foreach($data as $field=>$val){
                    if(!in_array($field,$allow_update_field)){
                        unset($data[$field]);
                    }
                }
            }
            //不允许修改字段
            if($this->no_allow_update_field){
                foreach($this->no_allow_update_field as $field){
                    unset($data[$field]);
                }
            }
            //dump($allow_update_field);dump($data);exit;
            // 更新数据
            $pk = $model->getPk();
            $id = $_REQUEST [$pk] ? : $_REQUEST ['id'];
            if (!is_array($id)) {
                $ids = explode(',', $id);
            } else {
                $ids = $id;
            }
            $wdata = array($pk => array('in', $ids));
            unset($data[$pk]);
            $list = $model->where($wdata)->save($data);
            if (false !== $list) {
                $pk = $model->getPk();
                //之后执行
                if (method_exists($this, '_after_edit')) {
                    $vo = $model->find($id);
                    $this->_after_edit($vo);
                }
                //缓存判断(控制器)
                if (method_exists($this, 'GiveCache')) {
                    $this->GiveCache($_POST[$pk]);//无需提示
                }else if(method_exists($model, 'GiveCache')) {
                    $model->GiveCache($_POST[$pk]);//无需提示
                }
                $this->history($id);
                $vo = $model->find($id);
                $this->ajaxSucReturn($vo);
            } else {
                //错误提示
                $this->ajaxErrReturn('编辑失败'.M()->_sql());
            }
        } else {
            $this->ajaxSucReturn($vo);
        }
    }

    /**
     * 删除记录(物理删除)
     */
    public function fdel() {
        if ($this->allow_del != 1) {
            $this->ajaxErrReturn('不允许删除');
        }
        $model = D(CONTROLLER_NAME);
        if (!empty($model)) {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk] ? : $_REQUEST ['id'];
            if (isset($id)) {
                if (!is_array($id)) {
                    $ids = explode(',', $id);
                } else {
                    $ids = $id;
                }
                $wdata = array($pk => array('in', $ids));
                if (false !== $model->where($wdata)->delete()) {
                    foreach ($ids as $id) {
                        $this->history($id);
                    }
                    //缓存判断
                    if (method_exists($this, 'GiveCache')) {
                        $this->GiveCache();
                    }
                    if (method_exists($this, '_after_fdel')) {
                        $this->_after_fdel($ids);
                    }
                    $this->ajaxSucReturn('删除成功！');
                } else {
                    $this->ajaxErrReturn('删除失败！');
                }
            } else {
                $this->ajaxErrReturn('非法操作');
            }
        }
    }

    /**
     * 删除记录(逻辑删除)
     */
    public function vdel() {
        //删除指定记录
        $name = CONTROLLER_NAME;
        $model = D($name);
        if (!empty($model)) {
            $pk = $model->getPk();
			$id = $_REQUEST [$pk];
            if (isset($id)) {
                if (!is_array($id)) {
                    $ids = explode(',', $id);
                } else {
                    $ids = $id;
                }
                $condition = array($pk => array('in', $ids));
                $condition['uid'] = UID;
                $list = $model->where($condition)->select();
                if(!$list){
                    $this->ajaxErrReturn('数据不存在！');
                }
                $sdata['is_delete'] = 1;
                $sdata['del_time'] = NOW_TIME;
                $sdata['del_aid'] = UID;//管理员id
                $sdata['del_aname'] = $u_msg['name'] ?  : '';//管理员名称
                if (false !== $model->where($condition)->save($sdata)) {
                    foreach ($ids as $id) {
                        $this->history($id);
                    }
                    //缓存判断
                    if (method_exists($this, 'GiveCache')) {
                        $this->GiveCache();
                    }
                    if (method_exists($this, '_after_vdel')) {
                        $this->_after_vdel($_REQUEST ['key']);
                    }
                    $this->ajaxSucReturn('删除成功！');
                } else {
                    $this->ajaxErrReturn('删除失败！');
                }
            } else {
                $this->ajaxErrReturn('非法操作');
            }
        }
    }

    /**
     * 删除记录(逻辑删除)
     */
    public function vdel_old() {
        //删除指定记录
        $name = CONTROLLER_NAME;
        $model = D($name);
        if (!empty($model)) {
            $pk = $model->getPk();
			$id = $_REQUEST [$pk];
            if (isset($id)) {
                if (!is_array($id)) {
                    $ids = explode(',', $id);
                } else {
                    $ids = $id;
                }
                $condition = array($pk => array('in', $ids));
                $sdata['deletetime'] = NOW_TIME;
                $list = $model->where($condition)->select();
                if(!$list){
                    $this->ajaxErrReturn('数据不存在！');
                }
                if (false !== $model->where($condition)->save($sdata)) {
                    foreach ($ids as $id) {
                        $this->history($id);
                    }
                    //缓存判断
                    if (method_exists($this, 'GiveCache')) {
                        $this->GiveCache();
                    }
                    if (method_exists($this, '_after_vdel')) {
                        $this->_after_vdel($_REQUEST ['key']);
                    }
                    $this->ajaxSucReturn('删除成功！');
                } else {
                    $this->ajaxErrReturn('删除失败！');
                }
            } else {
                $this->ajaxErrReturn('非法操作');
            }
        }
    }

    //成品规格添加编辑
    function addData(){
        $sqls = array();
        $request = I('');
        $model = D('DesigenGuigedetail');
        $model->startTrans();//启用事务
        if(CONTROLLER_NAME=='DesigenList'){
            //成品
            $atype = 1;
            $d_model = M("DesigenList");
        }else if(CONTROLLER_NAME=='Img'){
            //主辅料
            $atype = 2;
            $d_model = M("Img");
        }else if(CONTROLLER_NAME=='KuerpOtherProduct'){
            //其他商品
            $atype = 10;
            $d_model = M("KuerpOtherProduct");
        }else{
            $this->ajaxErrReturn('不存在的类型');
        }
        $data = $d_model->create();
        //dump($data);exit;
        if (false === $data) {
            $this->ajaxErrReturn($d_model->getError());
        }
        if(I('type')!=2 && (!I('guige_ids') || !I('color_ids'))){
            $this->ajaxErrReturn('规格和颜色必须都有');
        }
        if(!I('goods_sn')){
            $this->ajaxErrReturn('货号必须');
        }
        if(I('status')==2){
            //主辅料
            $wdata['title'] = I('title');
        }
        $wdata['is_delete'] = 0;
        $wdata['goods_sn'] = I('goods_sn');
        $count = $d_model->where($wdata)->count();
        if($count>0){
            $this->ajaxErrReturn('货号已存在');
        }
        $data['draw_pic'] = I('draw_pic') ? : '';
        $data['picc'] = I('picc') ? : '';
        $data['goods_attr'] = I('goods_attr') ? : '';
        //dump($data);exit;
        $design_id = $d_model->add($data);
        if(!$design_id){
            $this->ajaxErrReturn('商品不存在');
        }
        $sqls[] = M()->_sql();
        $c_model = M('Color');
        $i_model = M('Imgcate');
        $color_ids = I('color_ids');
        $guige_ids = I('guige_ids');
        foreach($color_ids as $k=>$color_id){
            if(!$color_id){
                unset($color_ids[$k]);
            }
        }
        foreach($guige_ids as $k=>$guige_id){
            if(!$guige_id){
                unset($guige_ids[$k]);
            }
        }
        if(I('type')!=2 && ($color_ids || $guige_ids)){
            $c_model = M("Color");
            $i_model = M("Imgcate");
            //笛卡尔积数组
            $new_arr[] = $color_ids;
            $new_arr[] = $guige_ids;
            if($atype==2 && (count($color_ids)>1 || count($guige_ids)>1)){
                $this->ajaxErrReturn('主辅料只能提交一种规格,一种颜色');
            }
            $dkes = $this->dikaer($new_arr);
            foreach($dkes as $dke){
                $input = array();
                $input['atype'] = $atype;
                $input['design_id'] = $design_id;
                $color_id = $dke[0];
                $guige_id = $dke[1];
                //规格名称
                $i_wdata['id'] = $guige_id;
                $guige = $i_model->where($i_wdata)->getField('title');
                if(!$guige){
                    $this->ajaxErrReturn('规格不存在');
                }
                //颜色名称
                $c_wdata['id'] = $color_id;
                $color = $c_model->where($c_wdata)->getField('names');
                if(!$color){
                    $this->ajaxErrReturn('颜色不存在');
                }
                //判断同规格是否存在
                $t_wdata['atype'] = $atype;
                $t_wdata['design_id'] = $design_id;
                $t_wdata['color_id'] = $color_id;
                $t_wdata['guige_id'] = $guige_id;
                $t_wdata['is_delete'] = 0;
                $t_count = $model->where($t_wdata)->count();
                if($t_count>0){
                    $this->ajaxErrReturn('有规格存在');
                }
                $input['color_id'] = $color_id;
                $input['guige_id'] = $guige_id;
                $input['color'] = $color ? : '';
                $input['guige'] = $guige ? : '';
                $input['goods_sn'] = $request['goods_sn'];
                $input['goods_attr'] = $request['goods_attr'] ? : '';
                $input['chenfen'] = $request['chenfen'];
                $input['unit'] = $request['unit'] ? : '';
                $input['price'] = $request['price'] ? : 0;
                $input['is_tax'] = $request['is_tax'] ? : 0;
                //添加
                $input['add_time'] = NOW_TIME;
                $id = $model->add($input);
                if(!$id){
                    $this->ajaxErrReturn('添加失败');
                }
                $sqls[] = M()->_sql();
            }
        }else{
            //给默认规格
            $input = array();
            $input['atype'] = $atype;
            $input['design_id'] = $design_id;
            $input['color_id'] = 0;
            $input['guige_id'] = 0;
            $input['color'] = '';
            $input['guige'] = '';
            $input['goods_sn'] = $request['goods_sn'];
            $input['goods_attr'] = $request['goods_attr'];
            $input['chenfen'] = $request['chenfen'];
            $input['unit'] = $request['unit'] ? : '';
            $input['price'] = $request['price'] ? : 0;
            $input['is_tax'] = $request['is_tax'];
            //添加
            $input['add_time'] = NOW_TIME;
            //dump($input);
            $id = $model->add($input);
            if(!$id){
                $this->ajaxErrReturn('添加失败');
            }
            $sqls[] = M()->_sql();
        }
        //dump($guige_ids);dump($color_ids);
        $d_wdata['id'] = $design_id;
        if(I('type')!=2 && $guige_ids && $guige_ids){
            $d_sdata['guige_ids'] = implode(',',$guige_ids);
            $d_sdata['color_ids'] = implode(',',$color_ids);
            $res = $d_model->where($d_wdata)->save($d_sdata);
            $sqls[] = M()->_sql();
        }
		//后置执行
        if (method_exists($this, '_after_'.ACTION_NAME)) {
            $r = $this->_after_add($list);
            if(!$r){
                $this->error('出错');
            }
        }
        //dump($sqls);exit;
        $model->commit();//提交事务
        $this->ajaxSucReturn($design_id);
    }

    //成品规格编辑
    function editData(){
        $request = I('');
        $id = I('id');
        if(CONTROLLER_NAME=='DesigenList'){
            //成品
            $atype = 1;
            $d_model = M("DesigenList");
            $d_wdata['id'] = $id;
            $vo = $d_model->where($d_wdata)->find();
        }else if(CONTROLLER_NAME=='Img'){
            //主辅料
            $atype = 2;
            $d_model = M("Img");
            $d_wdata['id'] = $id;
            $vo = $d_model->where($d_wdata)->find();
        }else if(CONTROLLER_NAME=='KuerpOtherProduct'){
            //其他商品
            $atype = 10;
            $d_model = M("KuerpOtherProduct");
            $d_wdata['id'] = $id;
            $vo = $d_model->where($d_wdata)->find();
        }else{
            $this->ajaxErrReturn('不存在的类型');
        }
        if(!$vo){
            $this->ajaxErrReturn('商品不存在');
        }
        $design_id = $vo['id'];
        $d_model->startTrans();//启用事务
        $data = $d_model->create();
        if (false === $data) {
            $this->ajaxErrReturn($d_model->getError());
        }
        $data['draw_pic'] = I('draw_pic') ? : '';
        $data['picc'] = I('picc') ? : '';
        // 更新数据
        $pk = $d_model->getPk();
        $id = $_REQUEST [$pk] ? : $_REQUEST ['id'];
        $wdata = array($pk => $id);
        unset($data[$pk]);
        $list = $d_model->where($wdata)->save($data);
        $sqls[] = M()->_sql();
        /*
        if(I('type')!=2 && $guige_names_filter && $color_names_filter){
            $c_model = M("Color");
            $i_model = M("Imgcate");
            $guige_names_filter = str_ireplace('，',',',I('guige_names'));
            $color_names_filter = str_ireplace('，',',',I('color_names'));
            $guige_names = explode(',',$guige_names_filter);
            $color_names = explode(',',$color_names_filter);
            foreach($guige_names as $key=>$guige){
                //规格
                $gg_wdata['status'] = 5;
                $gg_wdata['title'] = $guige_names[$key];
                $gg_vo = $i_model->where($gg_wdata)->find();
                if($gg_vo){
                    $guige_id = $gg_vo['id'];//规格id
                }else{
                    $guige_id = $i_model->add($gg_wdata);
                    $sqls[] = M()->_sql();
                }
                $guige_ids[] = $guige_id;
                $guiges[$guige_id] = $guige_names[$key];
            }
            foreach($color_names as $key=>$guige){
                //颜色
                $c_wdata['names'] = $color_names[$key];
                $c_vo = $c_model->where($c_wdata)->find();
                if($c_vo){
                    $color_id = $c_vo['id'];//颜色id
                }else{
                    $color_id = $c_model->add($c_wdata);
                    $sqls[] = M()->_sql();
                }
                $color_ids[] = $color_id;
                $colors[$color_id] = $color_names[$key];
            }
            //dump($colors);dump($guiges);exit;
            //笛卡尔积数组
            $new_arr[] = $color_ids;
            $new_arr[] = $guige_ids;
            $dkes = $this->dikaer($new_arr);
            $guige_ids_str = implode(',',$guige_ids);
            $color_ids_str = implode(',',$color_ids);
            $dg_model = D('DesigenGuigedetail');
            if($vo['guige_ids']==$guige_ids_str && $vo['color_ids']==$color_ids_str){
                $dg_wdata['atype'] = $atype;
                $dg_wdata['design_id'] = $vo['id'];
                $sdata2['goods_sn'] = $request['goods_sn'];
                $sdata2['goods_attr'] = $request['goods_attr'];
                $sdata2['chenfen'] = $request['chenfen'];
                $sdata2['price'] = $request['price'];
                $sdata2['unit'] = $request['unit'] ? : '';
                $sdata2['is_tax'] = $request['is_tax'];
                $r = $dg_model->where($dg_wdata)->save($sdata2);
                //echo M()->_sql();exit;
            }else{
                //重新生产规格
                //全部改为删除
                $dg_wdata['atype'] = $atype;
                $dg_wdata['design_id'] = $vo['id'];
                $dg_sdata['is_delete'] = 1;
                $r = $dg_model->where($dg_wdata)->save($dg_sdata);
                $sqls[] = M()->_sql();
                foreach($dkes as $dke){
                    $input = array();
                    $input['atype'] = $atype;
                    $input['design_id'] = $design_id;
                    $color_id = $dke[0];
                    $guige_id = $dke[1];
                    $input['color_id'] = $color_id;
                    $input['guige_id'] = $guige_id;
                    $count = $dg_model->where($input)->count();
                    if($count==0){
                        $input['color'] = $colors[$color_id];
                        $input['guige'] = $guiges[$guige_id];
                        //$input['sort'] = $request['sort'][$key] ? : 200;
                        //if($request['pic'][$key])$input['pic'] = $request['pic'][$key];
                        //$input['warn_number'] = $request['warn_number'][$key];
                        $input['goods_sn'] = $request['goods_sn'];
                        $input['goods_attr'] = $request['goods_attr'];
                        $input['chenfen'] = $request['chenfen'];
                        $input['price'] = $request['price'];
                        $input['is_tax'] = $request['is_tax'];
                        $input['unit'] = $request['unit'] ? : '';
                        //添加
                        $input['add_time'] = NOW_TIME;
                        //dump($input);
                        $id = $dg_model->add($input);
                        if(!$id){
                            $this->ajaxErrReturn('添加失败');
                        }
                    }else{
                        //存在的恢复
                        $sdata2['goods_sn'] = $request['goods_sn'];
                        $sdata2['goods_attr'] = $request['goods_attr'];
                        $sdata2['chenfen'] = $request['chenfen'];
                        $sdata2['price'] = $request['price'];
                        $sdata2['unit'] = $request['unit'] ? : '';
                        $sdata2['is_tax'] = $request['is_tax'];
                        $sdata2['is_delete'] = 0;
                        $r = $dg_model->where($input)->save($sdata2);
                    }
                    $sqls[] = M()->_sql();
                }
            }
        }
        */
        $dg_model = D('DesigenGuigedetail');
        $dg_wdata['atype'] = $atype;
        $dg_wdata['design_id'] = $id;
        $sdata2['goods_sn'] = $request['goods_sn'];
        $sdata2['goods_attr'] = $request['goods_attr'];
        $sdata2['chenfen'] = $request['chenfen'];
        $sdata2['price'] = $request['price'];
        $sdata2['unit'] = $request['unit'] ? : '';
        $sdata2['is_tax'] = $request['is_tax'];
        //$sdata2['is_delete'] = 0;
        $r = $dg_model->where($dg_wdata)->save($sdata2);
        if($atype==2){
            //辅料备货信息修改
            $pof_model = M('ProductionOrderFuliao');
            $pof_wdata['product_id'] = $id;
            $r = $pof_model->where($pof_wdata)->save($sdata2);
            //echo M()->_sql();exit;
        }
        //echo M()->_sql();
        $d_wdata['id'] = $vo['id'];
        $color_ids = I('color_ids');
        $guige_ids = I('guige_ids');
        if(I('type')!=2 && $color_ids && $guige_ids){
            $d_sdata['guige_ids'] = implode(',',$guige_ids);
            $d_sdata['color_ids'] = implode(',',$color_ids);
        }else{
            $d_sdata['guige_ids'] = '';
            $d_sdata['color_ids'] = '';
        }
        $res = $d_model->where($d_wdata)->save($d_sdata);
        $sqls[] = M()->_sql();
        //dump($sqls);exit;
        $d_model->commit();//启用事务
        $this->ajaxSucReturn('更新完成');
    }

    //笛卡尔积
    function dikaer($arr){ 
        $arr1 = array(); 
        $result = array_shift($arr); 
        while($arr2 = array_shift($arr)){ 
          $arr1 = $result; 
          $result = array(); 
          foreach($arr1 as $v){
            foreach($arr2 as $v2){
                if(!is_array($v))$v = array($v);
                if(!is_array($v2))$v2 = array($v2);
                $result[] = array_merge_recursive($v,$v2);
            } 
          } 
        } 
        return $result; 
    }

    /**
     * 检查是否有文件上传
     */
    public function checkFileUp() {
        foreach ($_FILES as $key => $val) {
            if ($val['name']) {
                return true;
            }
        }
        return false;
    }

    //历史操作记录
    function history($id, $action = '', $controller = '', $info = '', $desc = ''){
        // $h_model = M('History');
        // $data['controller'] = $controller ? $controller : CONTROLLER_NAME;
        // $data['action'] = $action ? $action : ACTION_NAME;
        // //行为列表
        // /*
        // $actions = F('AuthRuleList');
        // $action = $data['controller'].'/'.$data['action'];
        // $data['action_name'] = $actions[$action] ? $actions[$action]['title'] : '';
        // */
        // $data['aid'] = UID;
        // $data['name'] = $this->uinfo['names'];
        // $data['add_time'] = NOW_TIME;
        // $data['resource_id'] = $id;
        // //记录详细更新内容
        // if (!$info) {
        //     $map = array();
        //     $model = D($data['model']);
        //     $dbFields = $model->getDbFields();
        //     foreach ($dbFields as $key => $val) {
        //         if (isset($_POST [$val]) && $_POST [$val] != '') {
        //             //$this->assign($val,$_POST [$val]);
        //             $map [$val] = $_POST [$val];
        //         }
        //     }
        // } else {
        //     $map = $info;
        // }
		// unset($_POST['button']);
        // $data['info'] = serialize($_POST);
        // $data['rawdata'] = '';//原始数据
        // $data['desc'] = $desc;//日志说明
        // $data['ip'] = $_SERVER['REMOTE_ADDR'];
        // $h_model->add($data);
		return true;
    }

	//基本信息
	function baseInfo(){
        $name = CONTROLLER_NAME;
        $model = $model ? : D($name);
		$pk = $model->getPk();
        $vo = $model->find(I($pk));
		if($vo){
			if (method_exists($this, '_after_detail')) {
				$this->_after_detail($list);
			}
			$return['status'] = 1;
			$return['msg'] = '请求成功';
			$return['data'] = $vo;
			$this->ajaxSucReturn($return);		
		}else{
			$this->ajaxErrReturn('请求数据不存在');	
		}
	}

	//详情页
	function detail(){
        $name = CONTROLLER_NAME;
        $model = $model ? : D($name);
		$pk = $model->getPk();
        $wdata[$pk] = I($pk);
        $wdata['uid'] = UID;
        $vo = $model->where($wdata)->find();
        if(!$vo){
            $this->ajaxErrReturn('请求数据不存在');	
        }
		if($vo){
			if (method_exists($this, '_after_detail')) {
				$this->_after_detail($list);
			}
			$return['status'] = 1;
			$return['msg'] = '请求成功';
			$return['data'] = $vo;
			$this->ajaxSucReturn($return);		
		}else{
			$this->ajaxErrReturn('请求数据不存在');	
		}
	}


    public function _empty(){
        if(IS_AJAX){
            $json_data['code'] = 0;
            $json_data['status'] = 0;
            $json_data['msg'] = '请求数据错误';
            $this->ajaxErrReturn($json_data);
        }else{
            $this->ajaxErrReturn('你请求的页面不存');
        }
    }



    /**
     * 默认跳转操作 支持错误导向和正确跳转
     * 调用模板显示 默认为public目录下面的success页面
     * 提示页面为可配置 支持模板标签
     * @param string $message 提示信息
     * @param Boolean $status 状态
     * @param string $jumpUrl 页面跳转地址
     * @param mixed $ajax 是否为Ajax方式 当数字时指定跳转时间
     * @access private
     * @return void
     */
    private function dispatchJump($message,$status=1,$jumpUrl='',$ajax=false) {
        if(true === $ajax || IS_AJAX) {// AJAX提交
            $data           =   is_array($ajax)?$ajax:array();
            $data['msg']   =   $message;
            $data['status'] =   $status;
            $data['url']    =   $jumpUrl;
            $this->ajaxReturn($data);
        }
        if(is_int($ajax)) $this->assign('waitSecond',$ajax);
        if(!empty($jumpUrl)) $this->assign('jumpUrl',$jumpUrl);
        // 提示标题
        $this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_'));
        //如果设置了关闭窗口，则提示完毕后自动关闭窗口
        if($this->get('closeWin'))    $this->assign('jumpUrl','javascript:window.close();');
        $this->assign('status',$status);   // 状态
        //保证输出不受静态缓存影响
        C('HTML_CACHE_ON',false);
        if($status) { //发送成功信息
            $this->assign('message',$message);// 提示信息
            // 成功操作后默认停留1秒
            if(!isset($this->waitSecond))    $this->assign('waitSecond','1');
            // 默认操作成功自动返回操作前页面
            if(!isset($this->jumpUrl)) $this->assign("jumpUrl",$_SERVER["HTTP_REFERER"]);
            $this->display(C('TMPL_ACTION_SUCCESS'));
        }else{
            $this->assign('error',$message);// 提示信息
            //发生错误时候默认停留3秒
            if(!isset($this->waitSecond))    $this->assign('waitSecond','3');
            // 默认发生错误的话自动返回上页
            if(!isset($this->jumpUrl)) $this->assign('jumpUrl',"javascript:history.back(-1);");
            $this->display(C('TMPL_ACTION_ERROR'));
            // 中止执行  避免出错后继续执行
            exit ;
        }
    }


    function GetRandStr($length){
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randStr = str_shuffle($str);//打乱字符串
        $rands= substr($randStr,0,$length);//substr(string,start,length);返回字符串的一部分
        return $rands;
    }

    function getEncryptPassword($password, $salt = ''){
        return md5(md5($password) . $salt);
    }


}
